﻿using FluentValidation;
using System;
using System.Collections.Concurrent;
using System.Linq.Expressions;
namespace WebApplication2.Attribute
{

    public class BaseValidator<T> : AbstractValidator<T>
    {

        public BaseValidator()
        {
            var type = typeof(T).BaseType;
            if (type.Name!="BaseModel")
            {
                return;
            }
            var idExp = GetExpression<T, int>("ids");
            RuleFor(idExp).NotEmpty().WithMessage("id 不能为空");
            var nameExp = GetExpression<T, string>("name");
            RuleFor(nameExp).NotEmpty().WithMessage("name 不能为空");
        }

        public static Expression<Func<TIn, TOut>> GetExpression<TIn, TOut>(string propertyName)
        {
            ParameterExpression parameter = Expression.Parameter(typeof(T), "p");
            MemberExpression member = Expression.PropertyOrField(parameter, propertyName);
            return Expression.Lambda<Func<TIn, TOut>>(member, parameter);
        }
    }
}
